package service

import (
	"errors"
	"go-backend-simple-scaffold/model/entity"
	"go-backend-simple-scaffold/repository"
	"go-backend-simple-scaffold/utils"
	"gorm.io/gorm"
)

type UserService struct {
}

func (us *UserService) Register(u entity.GbssUser) (resp entity.GbssUser, err error) {
	var user *entity.GbssUser
	user, err = repository.ReposGroupApp.FindByUsername(u.UserName)
	// 判断用户是否注册
	// errors.Is() 判断一个错误是否等于另外一个错误
	// ErrRecordNotFound 查询时没有找到任何记录
	if !errors.Is(err, gorm.ErrRecordNotFound) || user != nil {
		return resp, errors.New("用户已经注册")
	}
	// 密码加密
	u.PassWord = utils.BcryptHash(u.PassWord)
	u.ID = utils.SnowGenId()
	err = repository.ReposGroupApp.Create(&u)
	return u, err
}
